
import json
import random
from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render,redirect,HttpResponse


from app02 import models
from app02.utils.pegination import Pegination
from app02.utils.bootrsap import BootrsapModelForm

class OrderModelForm(BootrsapModelForm):
    class Meta:
        model =models.Order
        #排除订单号
        exclude=['oid','adminUser']

def order_list(request):
    #新建订单列表
    form=OrderModelForm()

    #搜索框
    seach_list={}
    seach_data=request.GET.get('q','')
    if seach_data:
        seach_list['title__contains']=seach_data
    #获取数据库中的信息
    data_list=models.Order.objects.filter(**seach_list)
    #分页
    page_object=Pegination(request,data_list)
    coxtent={
        'form':form,
        'page_string':page_object.html(),  #生成页数据
        'seach_data':seach_data,  #生成页码
        'data_list':page_object.page_mun
    }


    return render(request,'order_list.html',coxtent)

@csrf_exempt
def order_add(request):
    """新建订单(ajax请求)"""
    form=OrderModelForm(data=request.POST)
    if form.is_valid():
        # 随机生成订单号
        form.instance.oid=datetime.now().strftime('%Y%m%d%H%M%S')+ str(random.randint(1000,9999))
        #固定设置管理员ID
        form.instance.adminUser_id=request.session['info']['id']
        form.save()
        return HttpResponse(json.dumps({'stuat':True}))
    return HttpResponse( json.dumps( {'stuat': False,'error':form.errors}))

#删除订单
def order_delete(request):
    uid=request.GET.get('uid')
    exists=models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({'stuat':False,'error':'删除失败，数据不存在。'})
    models.Order.objects.filter( id=uid ).delete()
    return JsonResponse( {'stuat':True} )

#编辑订单窗口
def order_deatil(request):
    # 获取id
    uid=request.GET.get('uid')
    """根据id获取到对应行信息数据"""
    row_dict=models.Order.objects.filter(id=uid).values('title','price','status').first()
    # 判断数据不存在
    if not row_dict:
        return JsonResponse( {'stuat': False, 'error': '数据不存在'} )
    result={
        'stuat':True,
        'data':row_dict
    }
    return JsonResponse(result)

#编辑订单
@csrf_exempt
def order_edit(request):
    # 获取id
    uid=request.GET.get('uid')
    row_object=models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse( {'stuat': False, 'tpis':'数据不存在'} )
    form=OrderModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse( {'stuat':True} )
    return HttpResponse( json.dumps( {'stuat': False, 'error': form.errors} ) )